package com.example.workflow.exception;


import com.example.workflow.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理自定义异常
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseEntity<Result<String>> handleCustomException(ServiceException ex) {
//            public void handleCustomException(ServiceException ex) {
        log.warn("自定义异常处理,{}",ex.getMessage());
        return new ResponseEntity<>(Result.error(HttpStatus.UNAUTHORIZED.value(), ex.getMessage()),HttpStatus.UNAUTHORIZED);

    }

    // 处理参数校验异常
    @ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<Result<String>> handleValidationException(org.springframework.web.bind.MethodArgumentNotValidException ex) {
        log.warn("参数错误,{}",ex.getMessage());
        String message = ex.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .findFirst().orElse("参数错误");
        return new ResponseEntity<>(Result.error(HttpStatus.BAD_REQUEST.value(), message),HttpStatus.BAD_REQUEST);
    }

    // 处理权限拒绝异常
    @ExceptionHandler(org.springframework.security.authorization.AuthorizationDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseEntity<Result<String>> handleAuthorizationDeniedException(org.springframework.security.authorization.AuthorizationDeniedException ex) {
        log.warn("权限拒绝异常: {}", ex.getMessage());
        return new ResponseEntity<>(Result.error(HttpStatus.FORBIDDEN.value(), "权限不足，请联系管理员"), HttpStatus.FORBIDDEN);
    }

    // 处理其他所有异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<Result<String>> handleException(Exception ex) {
        log.warn("自定义错误处理,{}",ex.getMessage());
//        throw new RuntimeException(ex);
        return new ResponseEntity<>(Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作失败, "+ex.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
